// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// U [author] rhyme_lph
// N [email]  rhymelph@gmail.com
// N [github] https://github.com/rhymelph

import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/widgets/button/ace_close_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/style/image_style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/camera/select_photo_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:path/path.dart' as path;
import 'package:pull_to_refresh/pull_to_refresh.dart';

@RouterMeta(paramName: "selectPhotoPage")
class SelectPhotoPage extends StatefulWidget {
  final bool isSelect;

  const SelectPhotoPage({Key key, this.isSelect: false}) : super(key: key);

  @override
  _SelectPhotoPageState createState() => _SelectPhotoPageState();
}

class _SelectPhotoPageState extends State<SelectPhotoPage>
    with PagePresenter<SelectPhotoPage, SelectPhotoProvider> {
  @override
  void initState() {
    super.initState();
    provider.isSelect = widget.isSelect;
  }

  @override
  Widget get buildWidget => listBuilder<bool>(
      builder: (BuildContext context, bool value, Widget child) =>
          value == true ? notPermissionPage() : normalPage(),
      selector: (_, __) => __.isShowError);

  Widget notPermissionPage() => Scaffold(
        backgroundColor: Colors.black,
        body: Stack(
          children: [
            Center(
              child: Text(
                '''To upload photos, you  need to allow access in 
Settings > Privacy > Photo''',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: getSp(20),
                  fontWeight: FontWeight.w700,
                  height: 24 / 20,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: getDp(20)),
              child: AceCloseButton(),
            ),
          ],
        ),
      );

  Widget normalPage() => Scaffold(
        appBar: CommonAppBar(
          backgroundColor: aceWhiteGreyColor,
          centerTitle: true,
          leadingWidth: getDp(80),
          titleSpacing: 0.0,
          leading: Center(
            child: PressedOpacityButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(
                S.current.cancel,
                style: TextStyle(
                  color: aceBlueColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 22 / 18,
                ),
                maxLines: 1,
              ),
            ),
          ),
          // title: buildTitleTab(),
        ),
        body: listBuilder<int>(
            builder: (BuildContext context, int value, Widget child) => value ==
                    0
                ? super.buildLoadingWidget
                : SmartRefresher(
                    controller: provider.refreshController,
                    onLoading: provider.onLoadMore,
                    enablePullDown: false,
                    enablePullUp: true,
                    child: GridView.builder(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          childAspectRatio: 1,
                          crossAxisSpacing: getDp(5),
                          mainAxisSpacing: getDp(5),
                          crossAxisCount: 3,
                        ),
                        itemCount: value,
                        itemBuilder: _buildPhotoItems),
                  ),
            selector: (_, __) => __.assetList.length),
      );

  Widget buildTitleTab() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) => SizedBox(
              width: getDp(168),
              child: CupertinoSegmentedControl<String>(
                onValueChanged: provider.onChangeTab,
                children: {
                  "Photos": Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: getDp(6),
                      vertical: getDp(3),
                    ),
                    child: Text(
                      S.current.photos,
                      style: TextStyle(
                        fontSize: getSp(14),
                        fontWeight: FontWeight.w700,
                        height: 20 / 14,
                      ),
                      maxLines: 1,
                    ),
                  ),
                  "Albums": Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: getDp(6),
                      vertical: getDp(3),
                    ),
                    child: Text(
                      S.current.albums,
                      style: TextStyle(
                        fontSize: getSp(14),
                        fontWeight: FontWeight.w700,
                        height: 20 / 14,
                      ),
                      maxLines: 1,
                    ),
                  ),
                },
                groupValue: value,
                selectedColor: aceDarkGrayColor,
                unselectedColor: Colors.white,
                pressedColor: aceDarkGrayColor,
                borderColor: Colors.transparent,
              ),
            ),
        selector: (_, __) => __.currentTab);
  }

  Widget _buildPhotoItems(BuildContext context, int index) {
    return listBuilder<AssetEntity>(
        builder: (BuildContext context, AssetEntity value, Widget child) =>
            FutureBuilder(future: value.file, builder: _buildImage),
        selector: (_, __) => __.assetList[index]);
  }

  Widget _buildImage(BuildContext context, AsyncSnapshot<File> snapshot) {
    return snapshot.hasData
        ? Stack(
            children: [
              Positioned.fill(
                  child: PressedOpacityButton(
                onPressed: () => provider.onSelectImage(snapshot.data),
                child: Image.file(
                  snapshot.data,
                  fit: BoxFit.cover,
                  frameBuilder: ImageStyle.fadeInFrame,
                ),
              )),
              Positioned(
                bottom: 0.0,
                left: 0.0,
                right: 0.0,
                child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: getDp(4),
                      vertical: getDp(4),
                    ),
                    color: aceBlackColor.withOpacity(0.25),
                    child: Text(
                      '${path.basename(snapshot.data.path)}',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: getSp(12),
                        fontWeight: FontWeight.w700,
                        height: 1,
                      ),
                    )),
              ),
            ],
          )
        : Container(
            color: aceWhiteGreyColor,
          );
  }
}
